package ctn.util;

import java.util.HashMap;
import java.util.Map;

import ctn.hibernate.po.ScoreRecord;

/**
 * Calculate the delay score
 * @author HLJ
 *
 */
public class RuleUtil {

	/**
	 * calculate Failed value
	 * @param maxLevel
	 * @param levelCount
	 * @return
	 */
	public static int getFailedValue(int maxLevel,int levelCount,int divide){
		int separated = maxLevel-levelCount;
		if (divide==0) {
			return 0;
		}
		return separated/divide;
	}
	
	/**
	 * calculate the delay score
	 * @param stage
	 * @param maxDelayDay
	 * @param npDiff
	 * @param stageSize
	 * @return ScoreRecord
	 */
	public static ScoreRecord userLevelSubtract(int stage,int maxDelayDay,int npDiff,int stageSize){
		Map<String, Integer> m = divideDelay(stageSize,maxDelayDay);
		long delayScore = 0L;
		ScoreRecord sr = new ScoreRecord();
		sr.setStage(new Long(stage));
		int i = (stage == 0?1:stage);
		for (; i <= stageSize; i++) {
			if (npDiff >= m.get(STAGE_LEVEL_CODE+i)) {
				delayScore++;
				sr.setStage(new Long(i));
			}else{
				break;
			}
			if(i==stageSize){
				if(npDiff > m.get(STAGE_LEVEL_CODE+i)){
					sr.setOverDelayDeadLine(true);
					delayScore = 0L;
					sr.setFailedValue(1L);
					sr.setStage(new Long(stageSize+1));
				}
			}
		}
		sr.setLevelValue(delayScore);
 		return sr;
	}
	
	/**
	 * divide the delay day to three part
	 * @param stage
	 * @param maxDelayDay
	 * @return
	 */
	private static Map<String, Integer> divideDelay(int stage,int maxDelayDay){
		int remainder = maxDelayDay%stage;
		int result = maxDelayDay/stage;
		Map<String, Integer> m = new HashMap<String, Integer>();
		int count = 1;
		for (int i = 0; i < maxDelayDay;) {
			if(remainder!=0){
				remainder--;
				i += (result+1);
			}else{
				i += result;
			}
			m.put(STAGE_LEVEL_CODE+count, i);
			count++;
		}
		return m;
	}
	
	private static final String STAGE_LEVEL_CODE = "stage_";
	
}
